package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.IPage;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.javaforge.tapestry.spring.annotations.InjectSpring;
import com.crm.service.IProcessService;
import com.crm.model.User;
import com.crm.model.Contact;

import java.util.List;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class ProcessInfo extends BasePage implements PageBeginRenderListener {

    private static Log log = LogFactory.getLog(ProcessInfo.class);
    private int count;

    @InjectSpring("processService")
    public abstract IProcessService getProcessService();

    @InjectState("userSession")
    public abstract User getUserSession();

    @InjectPage("CustomerSelect")
    public abstract CustomerSelect getCustomerSelectPage();

    @InjectPage("ProcessNew")
    public abstract ProcessNew getNewProcessPage();

    @InjectPage("ProcessModify")
    public abstract ProcessModify getProcessModifyPage();

    @Persist
    public abstract Contact getContactInfo();

    public abstract void setContactInfo(Contact contactInfo);

    public String getRecordCount() {
        return "共" + count + "条记录";
    }

    public List getEntries(){
        try{
            List list = getProcessService().getProcessByContactId(getContactInfo().getId());
            count = list.size();
            log.info(getUserSession().getUsername() + ": Get process information with 【" + getContactInfo().getCustomer().getCustomerName() +" - " + getContactInfo().getContactName() + "】");
            return list;
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public IPage newProcess(){
        ProcessNew page = getNewProcessPage();
        page.setContactInfo(getContactInfo());
        return page;
    }

    public IPage goback(){
        return getCustomerSelectPage();
    }

    public IPage onShowDetails(com.crm.model.Process process) {
        ProcessModify page = getProcessModifyPage();
        page.setProcess(process);
        page.setSourcePage(this.getPageName());
        return page;
    }

    public void pageBeginRender(PageEvent event) {
        if (null == getUserSession() || null == getContactInfo()) {
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
        }
    }

}
